package com.example.teachdemo4;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class ImageAsyncTaskActivity extends AppCompatActivity {
    ImageView iv_download;
    ProgressBar pb_loading;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_image_async_task);

        iv_download = findViewById(R.id.iv_download);
        pb_loading = findViewById(R.id.pb_loading);

    }

    public void imageDownload(View view) {
        String url = "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1608001369357&di=4024bde6afd73cb0755f130866292b72&imgtype=0&src=http%3A%2F%2Fimage.biaobaiju.com%2Fuploads%2F20190705%2F23%2F1562340403-CRfBloGesc.jpeg";

        new ImageAsyncTask().execute(url);
    }

    class ImageAsyncTask extends AsyncTask<String,Integer,Bitmap>{


        @Override
        protected void onPreExecute() {
            super.onPreExecute();

            pb_loading.setVisibility(View.VISIBLE);
        }

        @Override
        protected void onPostExecute(Bitmap bitmap) {
            super.onPostExecute(bitmap);
           iv_download.setImageBitmap(bitmap);
           pb_loading.setVisibility(View.GONE);
        }

        @Override
        protected void onProgressUpdate(Integer... values) {
            super.onProgressUpdate(values);
        }

        @Override
        protected Bitmap doInBackground(String... strings) {
            URL url = null;
            HttpURLConnection connection = null;
            InputStream is = null;

            Bitmap bitmap = null;
            try{
                url = new URL(strings[0]);
                connection = (HttpURLConnection) url.openConnection();

                is = connection.getInputStream();

                bitmap = BitmapFactory.decodeStream(is);


            }catch (Exception e){

            }
            return bitmap;
        }
    }

}
